package process

import (
	"../../common/message"
	"../../common/utils"
	"encoding/json"
	"fmt"
	"net"
)

type UserProcess struct {
}

func (this *UserProcess) Login(userId int, userPwd string) (err error) {

	conn, err := net.Dial("tcp", "localhost:8888")

	if err != nil {
		fmt.Printf("conn error = %v", err)
		return
	}

	defer conn.Close()

	var mes message.Message
	mes.Type = message.LoginMesType

	var loginMes message.LoginMes
	loginMes.UserId = userId
	loginMes.UserPwd = userPwd

	data, err := json.Marshal(loginMes)
	if err != nil {
		fmt.Printf("json marshal loginMes error = %v\n", err)
		return
	}

	mes.Data = string(data)

	data, err = json.Marshal(mes)
	if err != nil {
		fmt.Printf("json marshal mes error = %v\n", err)
		return
	}

	tf := &utils.Transfer{
		Conn: conn,
	}

	err = tf.WritePkg(data)
	if err != nil {
		fmt.Printf("conn write data error = %v\n", err)
		return
	}

	fmt.Printf("客户端发送消息内容 = %v\n", string(data))

	msg, err := tf.ReadPkg()
	if err != nil {
		fmt.Printf("readPkg error = %v\n", err)
		return
	}

	var loginResMes message.LoginResMes
	err = json.Unmarshal([]byte(msg.Data), &loginResMes)
	if err != nil {
		fmt.Printf("loginResMes json.Unmarshal error = %v\n", err)
		return
	}

	if loginResMes.Code == 200 {

		CurUser.Conn = conn
		CurUser.UserId = userId
		CurUser.UserStatus = message.UserOnline

		for _, v := range loginResMes.UserIds {
			if v == userId {
				continue
			}
			fmt.Println("在线用户id: \t", v)
			
			user := &message.User{UserId: v}
			onlineUserMap[user.UserId] = user
		}

		go serverProcessMes(conn)

		ShowMenu(userId)
		
	} else {
		fmt.Println(loginResMes.Error)
	}

	return
}

func (this *UserProcess) Register(userId int, userPwd string, userName string) (err error) {

	conn, err := net.Dial("tcp", "localhost:8888")

	if err != nil {
		fmt.Printf("conn error = %v", err)
		return
	}

	defer conn.Close()

	var mes message.Message
	mes.Type = message.RegisterMesType

	var registerMes message.RegisterMes

	var user message.User
	user.UserId = userId
	user.UserPwd = userPwd
	user.UserName = userName

	registerMes.User = user

	data, err := json.Marshal(registerMes)
	if err != nil {
		fmt.Printf("json marshal registerMes error = %v\n", err)
		return
	}

	mes.Data = string(data)

	data, err = json.Marshal(mes)
	if err != nil {
		fmt.Printf("json marshal mes error = %v\n", err)
		return
	}

	tf := &utils.Transfer{
		Conn: conn,
	}

	err = tf.WritePkg(data)
	if err != nil {
		fmt.Printf("conn write data error = %v\n", err)
		return
	}

	fmt.Printf("客户端发送消息内容 = %v\n", string(data))

	msg, err := tf.ReadPkg()
	if err != nil {
		fmt.Printf("readPkg error = %v\n", err)
		return
	}

	var registerResMes message.RegisterResMes
	err = json.Unmarshal([]byte(msg.Data), &registerResMes)
	if err != nil {
		fmt.Printf("registerResMes json.Unmarshal error = %v\n", err)
		return
	}

	if registerResMes.Code == 200 {
		fmt.Println("注册成功，你重新登录一把")
	} else {
		fmt.Println(registerResMes.Error)
	}

	return
}
